package com.feicheng.controller.wx;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feicheng.common.exception.SystemException;
import com.feicheng.common.result.ResultInfo;
import com.feicheng.common.task.Cache;
import com.feicheng.common.util.StringGenerator;
import com.feicheng.persistence.entity.*;
import com.feicheng.persistence.service.*;
import com.feicheng.service.AsyncService;
import com.feicheng.service.impl.FMjConnectionService;
import com.feicheng.wxapi.pay.WxAppPayBean;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDate;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cailongyang
 * @since 2024-08-21
 */
@RestController
@RequestMapping("/wx/yy")
public class YyController {

    @Autowired
    IAyyjlheadService iAyyjlheadService;

    @Autowired
    IAyyjlitemService iAyyjlitemService;

    @Autowired
    IAmdService iAmdService;

    @Autowired
    IAfjService iAfjService;

    @Autowired
    IClientService iClientService;

    @Autowired
    WxAppPayBean wxAppPayBean;

    @Autowired
    Cache cache;

    @Autowired
    AsyncService asyncService;

    @Autowired
    FMjConnectionService mjConnectionService;

    private String appid;

    @PostConstruct
    private void init() {
        Asetting asetting = cache.getObject("Asetting", Asetting.class);
        appid = asetting.getCappid();
    }

    @PostMapping("/item/post")
    public ResultInfo newYyjlitem(@RequestBody JSONObject param) {

        Ayyjlitem item = param.getObject("item", Ayyjlitem.class);

        Client client = iClientService.getById(item.getClientid());

        QueryWrapper<Ayyjlitem> qw = new QueryWrapper<>();
        qw.eq("fjid", item.getFjid());
        qw.eq("rq", item.getRq());
        qw.eq("pflg", true);
        qw.ne("statu", "C");
        qw.ne("statu", "P");

        qw.or(q -> {
            q.le("st", item.getSt()+":00");
            q.ge("et", item.getSt()+":00");
        });

        qw.or(q -> {
            q.le("st", item.getEt()+":00");
            q.ge("et", item.getEt()+":00");
        });

        qw.or(q -> {
            q.ge("st", item.getSt()+":00");
            q.le("et", item.getEt()+":00");
        });

        Amd amd = iAmdService.getById(item.getMdid());
        Afj afj = iAfjService.getById(item.getFjid());

        item.setYyjlitemid(StringGenerator.getID("YYIT"));
        item.setPflg(false);
        item.setYyjlheadid("DX");
        item.setStatu("");
        item.setMdmc(amd.getMdmc());
        item.setFjmc(afj.getFjmc());

        synchronized (item.getFjid().intern()) {
            long count = iAyyjlitemService.count(qw);
            if (count > 0) {
                throw new SystemException("当前时间段已经被占用，请重新选择");
            }

            if (item.getSfje() > 0) {
                PrepayWithRequestPaymentResponse prepayData =
                        wxAppPayBean.jsapi(
                                item.getYyjlitemid(),
                                "预约订单",
                                "/notice-url/"+item.getYyjlitemid(),
                                item.getSfje(),
                                client.getOpenid(),
                                "",
                                appid
                        );
                String prepayId = prepayData.getPackageVal().split("=")[1];
                item.setPrepaydata(JSONObject.toJSONString(prepayData));
                item.setPrepayid(prepayId);
            }

            if (StringUtils.hasLength(item.getQid())) {
                // 核销逻辑
            }

            param.put("item", item);
            iAyyjlitemService.save(item);
        }

        asyncService.runScheduler(() -> {

            Ayyjlitem ayyjlitem = iAyyjlitemService.getById(item.getYyjlitemid());
            if (ayyjlitem.getPflg()) {
                ayyjlitem.setStatu("U");
                iAyyjlitemService.updateById(ayyjlitem);

                if (LocalDate.now().isEqual(ayyjlitem.getRq())) {
                    mjConnectionService.addSingelFacetoMdmj(ayyjlitem);
                }

                return "已支付，预约成功";
            } else {
                ayyjlitem.setStatu("C");
                iAyyjlitemService.updateById(ayyjlitem);
                return "已过时，预约取消";
            }

        }, 2, "预约记录支付核减：【"+item.getYyjlitemid()+"】");

        return ResultInfo.success(param);
    }

    @PostMapping("/item/count/get")
    public ResultInfo getYyitemcount(@RequestBody JSONObject param) {
        QueryWrapper<Ayyjlitem> qw = new QueryWrapper<>();
        String clientid = param.getString("clientid");
        if(!StringUtils.hasLength(clientid)) {
            throw new SystemException("客户ID缺失");
        }
        param.put("count", iAyyjlitemService.count(qw.eq("clientid", clientid)));

        qw.clear();
        param.put("ccount", iAyyjlitemService.count(qw.eq("clientid", clientid).eq("statu", "C")));

        qw.clear();
        param.put("ucount", iAyyjlitemService.count(qw.eq("clientid", clientid).eq("statu", "U")));

        qw.clear();
        param.put("rcount", iAyyjlitemService.count(qw.eq("clientid", clientid).eq("statu", "R")));

        qw.clear();
        param.put("pcount", iAyyjlitemService.count(qw.eq("clientid", clientid).eq("statu", "P")));

        return ResultInfo.success(param);
    }

    @PostMapping("/item/page/get")
    public ResultInfo getYyitemByPage(@RequestBody JSONObject param) {

        Integer current = param.getInteger("current");
        Integer size = param.getInteger("size");

        if (current == null || current < 0) {
            current = 1;
        }

        if (size == null || size < 0) {
            size = 16;
        }

        //构建分页
        IPage<Ayyjlitem> page = new Page<>(current, size);
        QueryWrapper<Ayyjlitem> qwitempage = new QueryWrapper<>();

        String statu = param.getString("statu");
        if (StringUtils.hasLength(statu)) {
            qwitempage.eq("statu", statu);
        }

        String rq = param.getString("rq");
        if (StringUtils.hasLength(rq)) {
            qwitempage.eq("rq", rq);
        }

        String srq = param.getString("srq");
        if (StringUtils.hasLength(srq)) {
            qwitempage.ge("rq", srq);
        }

        String erq = param.getString("erq");
        if (StringUtils.hasLength(erq)) {
            qwitempage.le("rq", erq);
        }

        String st = param.getString("st");
        if (StringUtils.hasLength(st)) {
            qwitempage.ge("st", st);
        }

        String et = param.getString("et");
        if (StringUtils.hasLength(et)) {
            qwitempage.le("et", et);
        }

        String clientid = param.getString("clientid");
        if (StringUtils.hasLength(clientid)) {
            qwitempage.eq("clientid", clientid);
        }

        String mdid = param.getString("mdid");
        if (StringUtils.hasLength(mdid)) {
            qwitempage.eq("mdid", mdid);
        }

        String fjid = param.getString("fjid");
        if (StringUtils.hasLength(fjid)) {
            qwitempage.eq("fjid", fjid);
        }

        page = iAyyjlitemService.page(page, qwitempage);
        param.put("yyjlitems", page);
        return ResultInfo.success(param);

    }

    @PostMapping("/item/list/get")
    public ResultInfo getYyitemByList(@RequestBody JSONObject param) {

        QueryWrapper<Ayyjlitem> qwitempage = new QueryWrapper<>();

        String statu = param.getString("statu");
        if (StringUtils.hasLength(statu)) {
            qwitempage.eq("statu", statu);
        }

        String rq = param.getString("rq");
        if (StringUtils.hasLength(rq)) {
            qwitempage.eq("rq", rq);
        }

        String srq = param.getString("srq");
        if (StringUtils.hasLength(srq)) {
            qwitempage.ge("rq", srq);
        }

        String erq = param.getString("erq");
        if (StringUtils.hasLength(erq)) {
            qwitempage.le("rq", erq);
        }

        String st = param.getString("st");
        if (StringUtils.hasLength(st)) {
            qwitempage.gt("et", st);
        }

        String et = param.getString("et");
        if (StringUtils.hasLength(et)) {
            qwitempage.lt("st", et);
        }

        String clientid = param.getString("clientid");
        if (StringUtils.hasLength(clientid)) {
            qwitempage.eq("clientid", clientid);
        }

        String mdid = param.getString("mdid");
        if (StringUtils.hasLength(mdid)) {
            qwitempage.eq("mdid", mdid);
        }

        String fjid = param.getString("fjid");
        if (StringUtils.hasLength(fjid)) {
            qwitempage.eq("fjid", fjid);
        }

        param.put("yyjlitems", iAyyjlitemService.list(qwitempage));
        return ResultInfo.success(param);
    }

    @PostMapping("/item/info/get")
    public ResultInfo getYyitemInfo(@RequestBody JSONObject param) {

        String yyjlitemid = param.getString("yyjlitemid");
        if (!StringUtils.hasLength(yyjlitemid)) {
            throw new SystemException("id必须指定");
        }

        Ayyjlitem item = iAyyjlitemService.getById(yyjlitemid);
        Amd md = iAmdService.getById(item.getMdid());
        Afj fj = iAfjService.getById(item.getFjid());

        param.put("yyjlitem", item);
        param.put("md", md);
        param.put("fj", fj);

        return ResultInfo.success(param);
    }

}

